package com.runshu.runshuwulian.ui.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hyphenate.easeui.mwidget.brvahrecyclerview.BaseQuickAdapter;
import com.hyphenate.easeui.mwidget.mutil.SystemBarManager;
import com.hyphenate.easeui.mwidget.qrscan.QRCodeView;
import com.hyphenate.easeui.mwidget.qrscan.zxing.ZXingView;
import com.runshu.runshuwulian.R;
import com.runshu.runshuwulian.base.BaseActivity;
import com.runshu.runshuwulian.base.net.BaseObserver;
import com.runshu.runshuwulian.base.net.RetrofitFactory;
import com.runshu.runshuwulian.bean.BaseBean;
import com.runshu.runshuwulian.bean.GoodsBean;
import com.runshu.runshuwulian.ui.adapter.ScanGoodsAdapter;
import com.runshu.runshuwulian.utils.UtilLoadImage;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class ScanGoodsActivity extends BaseActivity implements QRCodeView.Delegate {

    @BindView(R.id.view_scan)
    ZXingView viewScan;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.view_input)
    LinearLayout viewInput;
    @BindView(R.id.bt_sm)
    TextView btSm;
    @BindView(R.id.bt_shm)
    TextView btShm;
    @BindView(R.id.ly_bottom)
    LinearLayout lyBottom;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.bt_submit)
    TextView btSubmit;
    @BindView(R.id.ly_gwc)
    LinearLayout lyGwc;
    @BindView(R.id.layout_mycart)
    View layout_mycart;
    @BindView(R.id.bt_exit)
    ImageView btExit;
    @BindView(R.id.rv)
    RecyclerView rv;

    Map<String, GoodsBean> myCart = new HashMap<>();
    Runnable restart = () -> {
        viewScan.startSpot();
    };
    @BindView(R.id.bt_search)
    TextView btSearch;
    @BindView(R.id.iv)
    ImageView iv;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_code)
    TextView tvCode;
    @BindView(R.id.tv_cpgg)
    TextView tvCpgg;
    @BindView(R.id.tv_sccj)
    TextView tvSccj;
    @BindView(R.id.tv_gys)
    TextView tvGys;
    @BindView(R.id.bt_plus)
    ImageView btPlus;
    @BindView(R.id.layout_search_goods)
    LinearLayout layoutSearchGoods;
    @BindView(R.id.empty_view)
    LinearLayout emptyView;

    @Override
    protected int setContentViewResId() {
        return R.layout.activity_scan_goods;
    }

    ScanGoodsAdapter adapter;

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        super.initView( savedInstanceState );
        SystemBarManager.fullScreen( this );
        viewScan.setDelegate( this );
        adapter = new ScanGoodsAdapter( new ArrayList<>() );
        rv.setLayoutManager( new LinearLayoutManager( self() ) );
        rv.setAdapter( adapter );
        adapter.setOnItemChildClickListener( new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.bt_delete:
                        myCart.remove( ((GoodsBean) adapter.getData().get( position )).getId() );
                        refreshView();
                        break;
                }
            }
        } );
        setPage( 0 );
    }

    private void setPage(int position) {
        viewScan.setVisibility( position == 0 ? View.VISIBLE : View.GONE );
        viewInput.setVisibility( position != 0 ? View.VISIBLE : View.GONE );
        btSm.setSelected( position == 0 );
        btShm.setSelected( position != 0 );
        if (position != 0) {
            viewScan.stopSpot();
        } else {
            startScan();
        }
    }

    GoodsBean goodsBean;

    @OnClick({R.id.ly_gwc, R.id.bt_sm, R.id.bt_shm, R.id.bt_submit, R.id.bt_exit, R.id.bt_search, R.id.bt_clear, R.id.bt_plus
            , R.id.bt_dismiss_mycart})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ly_gwc:
                layout_mycart.setVisibility( layout_mycart.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE );
                break;
            case R.id.bt_dismiss_mycart:
                layout_mycart.setVisibility( View.GONE );
                break;
            case R.id.bt_sm:
                setPage( 0 );
                break;
            case R.id.bt_shm:
                setPage( 1 );
                break;
            case R.id.bt_search:
                searchByKey();
                break;
            case R.id.bt_clear:
                myCart.clear();
                refreshView();
                break;
            case R.id.bt_submit:
                break;
            case R.id.bt_plus:
                if (goodsBean != null) {
                    if (myCart.containsKey( goodsBean.getId() )) {
                        showShortToast( "您已添加此产品" );
                        break;
                    }
                    myCart.put( goodsBean.getId(), goodsBean );
                    refreshView();
                }
                break;
            case R.id.bt_exit:
                finishByDefaultAnim();
                break;
        }
    }


    public void searchGoods(String code, BaseObserver observer) {
        api().getGoodsInfoByCode( code ).compose( RetrofitFactory.threadTransformer() )
                .subscribe( observer );
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        Log.e( "yby-scan", result );
        showDefaultProgressDialog( true );
        searchGoods( result, new BaseObserver<GoodsBean>() {

            @Override
            protected void onSuccees(BaseBean<GoodsBean> response) throws Exception {
                dissmissProgressDialog();
                showShortToast( response.getMessage() );
                GoodsBean data = response.getData();
                if (data != null) {
                    myCart.put( data.getId(), data );
                    refreshView();
                }
                startScan();
            }

            @Override
            protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {
                dissmissProgressDialog();
                showShortToast( e.getMessage() );
                startScan();

            }
        } );
    }

    private void searchByKey() {
        if (TextUtils.isEmpty( etSearch.getText().toString() )) {
            showShortToast( "请输入产品编码" );
            goodsBean=null;
            refreshSearchView();
            return;
        }
        showDefaultProgressDialog( true );
        searchGoods( etSearch.getText().toString(), new BaseObserver<GoodsBean>() {
            @Override
            protected void onSuccees(BaseBean<GoodsBean> response) throws Exception {
                dissmissProgressDialog();
                if (response.getData() != null) {
                    goodsBean = response.getData();
                } else {
                    goodsBean = null;
                }
                refreshSearchView();
            }

            @Override
            protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {
                dissmissProgressDialog();
                goodsBean = null;
                showShortToast( e.getMessage() );
                refreshSearchView();
            }
        } );
    }

    private void refreshSearchView() {
        if (goodsBean != null) {
            layoutSearchGoods.setVisibility( View.VISIBLE );
            emptyView.setVisibility( View.GONE );
            UtilLoadImage.loadImage( self(), iv, goodsBean.getImageUrl() );
            tvName.setText( goodsBean.getProductName() );
            tvCode.setText( "流水码：" + goodsBean.getSerialNo() );
            tvCpgg.setText( "产品规格：" + goodsBean.getModel() );
            tvSccj.setText( "生产厂家：" + goodsBean.getProductVendorName() );
            tvGys.setText( "供应商：" + goodsBean.getSupplierName() );
        } else {
            layoutSearchGoods.setVisibility( View.GONE );
            emptyView.setVisibility( View.VISIBLE );
        }
    }

    private void startScan() {
        viewScan.postDelayed( restart
                , 1000 );
    }

    private void refreshView() {
        tvNum.setText( myCart.size() + "" );
        adapter.setNewData( new ArrayList<>( myCart.values() ) );
    }

    @Override
    protected void onResume() {
        super.onResume();
        viewScan.startSpot();
    }

    @Override
    protected void onStart() {
        super.onStart();
        viewScan.startCamera();
        viewScan.startSpotAndShowRect();
    }

    @Override
    protected void onPause() {
        super.onPause();
        viewScan.stopSpot();
    }

    @Override
    protected void onStop() {
        viewScan.stopCamera(); // 关闭摄像头预览，并且隐藏扫描框
        viewScan.removeCallbacks( restart );
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        viewScan.onDestroy();
        super.onDestroy();
    }

    @Override
    public void onCameraAmbientBrightnessChanged(boolean isDark) {

    }

    @Override
    public void onScanQRCodeOpenCameraError() {

    }

    @OnClick()
    public void onViewClicked() {
    }


}
